package com.demo.demo.service

import com.demo.demo.domain.Student
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.jdbc.core.BeanPropertyRowMapper
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.core.RowMapper
import org.springframework.stereotype.Service
import java.sql.ResultSet

interface StudentService {
    fun getAll(): List<Student>
    fun add(student: Student): Boolean
}

@Service
class StudentServiceImpl : StudentService {
    @Autowired
    private lateinit var jdbcTemplate: JdbcTemplate

    override fun getAll(): List<Student> {
        return jdbcTemplate.query(
            "SELECT * FROM student"
        ) { rs, _ ->
            val id = rs.getLong("id")
            val name = rs.getString("name_string") ?: ""
            val num = rs.getString("num") ?: ""
            val sex = rs.getString("sex")
            Student(id = id, num = num, nameString = name, sex = sex)
        }
    }

    override fun add(student: Student): Boolean {
        return jdbcTemplate.update(
            "INSERT INTO student (num,name_string,sex) VALUES (?,?,?)",
            student.num,
            student.nameString,
            student.sex
        ) > 0
    }
}